package com.fanshuai.spring.boot.local.mybatisplus.service;

import com.fanshuai.spring.boot.local.domain.User;
import com.fanshuai.spring.boot.local.mybatisplus.dao.UserDao;
import com.fanshuai.spring.boot.local.mybatisplus.dao.UserDao2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class MybatisPlusUserService {

    @Resource
    private UserDao userDao;
    @Resource
    private UserDao2 userDao2;

    @Resource
    private DataSourceTransactionManager transactionManager;
    @Resource(name = "transactionManager2")
    private DataSourceTransactionManager transactionManager2;
    @Resource
    private TransactionDefinition definition;

    public boolean batchAdd(List<User> users) {
        if (CollectionUtils.isEmpty(users)) {
            return true;
        }

        TransactionStatus transactionStatus = null;
        try {
            transactionStatus = transactionManager.getTransaction(definition);
            for (User user : users) {
                userDao.save(user);
            }
            transactionManager.commit(transactionStatus);
            return true;
        } catch (Exception e) {
            log.error("insert error, ", e);
            return false;
        } finally {
            if (null != transactionStatus && !transactionStatus.isCompleted()) {
                transactionManager.rollback(transactionStatus);
            }
        }
    }

    public boolean batchAdd2(List<User> users) {
        if (CollectionUtils.isEmpty(users)) {
            return true;
        }

        TransactionStatus transactionStatus = null;
        try {
            transactionStatus = transactionManager2.getTransaction(definition);
            for (User user : users) {
                userDao2.save(user);
            }
            transactionManager.commit(transactionStatus);
            return true;
        } catch (Exception e) {
            log.error("insert error, ", e);
            return false;
        } finally {
            if (null != transactionStatus && !transactionStatus.isCompleted()) {
                transactionManager.rollback(transactionStatus);
            }
        }
    }
}
